<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="菜单栏标题">
          <n-input v-model:value="search_param.key" placeholder="请输入菜单栏标题查询" style="width:230px"
                   clearable/>
        </n-form-item>
        <n-form-item label="教师专用">
          <n-select v-model:value="search_param.isTeacher" :options="teacherOption" style="width: 100px;" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" :options="statusOption" style="width: 100px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(search_param.key=null,search_param.status=null,search_param.isTeacher=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="uc_menu/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['uc_menu:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!--新增、修改 -->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改菜单栏':'新增菜单栏'" :mask-closable="false"
             :show-icon="false" preset="dialog" @after-leave="closeAddEditModel">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-width="auto" label-placement="left">
        <n-form-item label="标题" path="title">
          <n-input v-model:value="addEditForm.title" placeholder="请填写菜单栏标题" clearable/>
        </n-form-item>
        <n-form-item label="图标" path="icon">
          <image-selection v-model:value="addEditForm.icon" :width="60" :height="60"/>
        </n-form-item>
        <n-form-item label="类型" path="type">
          <n-radio-group v-model:value="addEditForm.type" name="typeOption">
            <template v-for="item in typeOption">
              <n-radio :value="item.value" :label="item.label"/>
            </template>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="链接" v-if="addEditForm.type==0" path="url" :rule="{
        required: true,
        message: `请填写菜单栏链接地址`,
        trigger: ['input', 'blur']
      }">
          <n-input v-model:value="addEditForm.url" placeholder="请填写菜单栏链接地址" clearable/>
        </n-form-item>
        <n-form-item label="电话" v-if="addEditForm.type==1" path="url" :rule="{
        required: true,
        message: `请填写电话号码`,
        trigger: ['input', 'blur']
      }">
          <n-input v-model:value="addEditForm.url" maxlength="12"
                   placeholder="请填写电话号码  如：0991-2526123或13999912345" clearable/>
        </n-form-item>
        <n-form-item label="图片" v-if="addEditForm.type==2" path="url" :rule="{
        required: true,
        message: `请选择图片`,
        trigger: ['input', 'blur']
      }">
          <image-selection v-model:value="addEditForm.url"/>
        </n-form-item>
        <n-form-item label="内容" v-if="addEditForm.type==3" path="url" :rule="{
        required: true,
        message: `请填写内容`,
        trigger: ['input', 'blur']
      }">
          <n-input
              placeholder="请填写内容"
              type="textarea"
              size="small"
              :autosize="{ minRows: 3, maxRows: 5}"/>
        </n-form-item>
        <!--        <n-form-item label="是否教师专用" path="isTeach">-->
        <!--          <n-radio-group v-model:value="addEditForm.isTeach" name="isDownload">-->
        <!--            <n-radio :value="1" label="是"/>-->
        <!--            <n-radio :value="0" label="否"/>-->
        <!--          </n-radio-group>-->
        <!--        </n-form-item>-->
        <n-form-item label="状态" path="status">
          <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="0" :unchecked-value="1">
            <template #checked>
              正常
            </template>
            <template #unchecked>
              停用
            </template>
          </n-switch>
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number v-model:value="addEditForm.sort" :show-button="false" placeholder="广告排序" clearable/>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>

</template>
<script setup lang="ts">
import {ref, reactive, h} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup/index.ts';
import {SelectOption, NPopconfirm, NImage, NTag, FormInst, useMessage} from 'naive-ui';
import DataTable from '@components/DataTable';
import DataTableAction from '@components/DataTable/src/components/DataTableAction/index.ts';

import {AddSharp} from '@vicons/material';
import {delRequest, postPutRequest} from '@/api/data.ts';


import ImageSelection from "@components/ImageSelection";
import {imagePreview} from '@/util';

const message = useMessage()


const statusOption = ref<SelectOption[]>([
  {
    label: '停用',
    value: 1,
  }, {
    label: '正常',
    value: 0,
  }
])
const teacherOption = ref<SelectOption[]>([
  {
    label: '是',
    value: 1,
  }, {
    label: '否',
    value: 0,
  }
])
const typeOption = ref<SelectOption[]>([
  {
    label: '页面',
    value: 0,
  }, {
    label: '电话',
    value: 1,
  },
  {
    label: '图片',
    value: 2,
  }, {
    label: '内容',
    value: 3,
  }, {
    label: '扫码',
    value: 4,
  }
])
const search_param = ref({
  key: null,
  isTeacher: null,
  status: null,
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '标题',
    key: 'title'
  }, {
    title: '图标',
    key: 'icon',
    width: 100,
    align: 'center',
    render(row: { icon: string }) {
      if (row.icon) {
        return h(NImage, {
          width: 30,
          height: 30,
          src: imagePreview(row.icon)
        })
      }
    }
  },
  // {
  //   title: '教师专用',
  //   key: 'isTeach',
  //   width: 100,
  //   align: 'center',
  //   render(row: { isTeach: number }) {
  //     const isTeachText = row.isTeach ? '是' : '否';
  //     return h('span', null, {default: () => (isTeachText)})
  //   }
  // },
  {
    title: '类型',
    key: 'type',
    width: 100,
    render(row: { type: number }) {
      const typeText:SelectOption| undefined  = typeOption.value.find(item=>item.value===row.type);
       return h('span', null, {default: () => (typeText && typeText.label)})
    }
  },
  {
    title: '链接/电话/图片/内容',
    key: 'url',
    render(row: { type: number,url:string }) {
      if(row.type==2) {
        return h(NImage, {
          width: 30,
          height: 30,
          src: imagePreview(row.url)
        })
      }
       return h('span', null, {default: () => (row.url)})
    }
  }, {
    title: '排序',
    key: 'sort',
    width: 90,

  }, {
    title: '状态',
    key: 'status',
    width: 90,
    align: 'center',
    render(row: { status: boolean | number }) {
      const enabled_text: SelectOption | undefined = statusOption.value.find(obj => obj.value === row.status);
      let enabled_color: any = row.status == 0 ? 'success' : 'warning';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text && enabled_text.label),
          }
      );
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }, {
    title: '更新时间',
    key: 'updateTime',
    width: 175,
  }
]);
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['uc_menu:edit'],
        }, {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前菜单栏信息吗？',
          },
          permission: ['uc_menu:del'],
        }
      ]
    });
  },
});
//新增、修改数据
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  title: <string | null | any>null,
  url: <string | null | any>null,
  icon: null,
  isTeach: 1,
  status: 0,
  type: 0,
  sort: 100,
})
const addEditFormRules = ref({
  title: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写菜单栏标题'
  },
  icon: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请填写菜单栏图标'
  }, type: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择类型'
  },
})

//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.title = record.title;
  addEditForm.value.url = record.url;
  addEditForm.value.icon = record.icon;
  addEditForm.value.isTeach = record.isTeach;
  addEditForm.value.status = record.status;
  addEditForm.value.sort = record.sort;
  addEditForm.value.type = record.type;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('uc_menu/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.title = null;
  addEditForm.value.url = null;
  addEditForm.value.icon = null;
  addEditForm.value.isTeach = 0;
  addEditForm.value.status = 0;
  addEditForm.value.sort = 100;
  addEditForm.value.type = 0;
  handelSubmitLoading.value = false;
}
//保存新增、修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'uc_menu/edit' : 'uc_menu/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
</script>
<style scoped lang="scss">

</style>